package com.nativescan

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Base64
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.google.mlkit.vision.barcode.BarcodeScanning
import com.google.mlkit.vision.barcode.common.Barcode
import com.google.mlkit.vision.common.InputImage
import com.nativemodules.NativeScanSpec
import java.io.ByteArrayOutputStream

class NativeScan(reactApplicationContext: ReactApplicationContext) : NativeScanSpec(reactApplicationContext) {
    private val scanner = BarcodeScanning.getClient()

    override fun getName() = NAME

    override fun scanBarcodeFromImage(image: String?, promise: Promise?) {
        if (image == null) {
            promise?.reject("INVALID_IMAGE", "Image data is null")
            return
        }

        try {
            // 解码 Base64 图片数据
            val imageBytes = Base64.decode(image, Base64.DEFAULT)
            val bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)

            if (bitmap == null) {
                promise?.reject("DECODE_ERROR", "Failed to decode image")
                return
            }

            // 创建 ML Kit 输入图像
            val inputImage = InputImage.fromBitmap(bitmap, 0)

            // 开始扫描
            scanner.process(inputImage)
                .addOnSuccessListener { barcodes ->
                    if (barcodes.isEmpty()) {
                        promise?.reject("NO_BARCODE", "No barcode found in image")
                        return@addOnSuccessListener
                    }

                    // 获取第一个条形码的结果
                    val barcode = barcodes[0]
                    val result = when (barcode.valueType) {
                        Barcode.TYPE_TEXT -> barcode.rawValue
                        Barcode.TYPE_URL -> barcode.url?.url
                        Barcode.TYPE_EMAIL -> barcode.email?.address
                        Barcode.TYPE_PHONE -> barcode.phone?.number
                        Barcode.TYPE_SMS -> barcode.sms?.message
                        Barcode.TYPE_WIFI -> {
                            val ssid = barcode.wifi?.ssid
                            val password = barcode.wifi?.password
                            "WIFI:S:$ssid;T:WPA;P:$password;;"
                        }
                        else -> barcode.rawValue
                    }

                    if (result != null) {
                        promise?.resolve(result)
                    } else {
                        promise?.reject("INVALID_BARCODE", "Invalid barcode format")
                    }
                }
                .addOnFailureListener { e ->
                    promise?.reject("SCAN_ERROR", e.message ?: "Failed to scan barcode")
                }

        } catch (e: Exception) {
            promise?.reject("PROCESS_ERROR", e.message ?: "Failed to process image")
        }
    }

    companion object {
        const val NAME = "NativeScan"
    }
}